package com.supermap.mouseListeners;

import com.supermap.Helper;
import com.supermap.data.GeoModel;
import com.supermap.data.GeoStyle3D;
import com.supermap.data.Rectangle2D;
import com.supermap.realspace.*;
import com.supermap.ui.*;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Layer3DsTreeMouseListener implements MouseListener {
    private final Layer3DsTree layer3DsTree;

    public Layer3DsTreeMouseListener(Layer3DsTree layer3DsTree) {
        this.layer3DsTree = layer3DsTree;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        Object source = e.getSource();
        if (!(source instanceof Layer3DsTree)) {
            return;
        }
        Layer3DsTree layer3DsTree = (Layer3DsTree) source;
        JPopupMenu popupMenu = layer3DsTree.getComponentPopupMenu();
        if (popupMenu != null) {
            popupMenu.removeAll();
            popupMenu.setVisible(false);
        }

        switch (e.getButton()) {
            // 鼠标左键
            case MouseEvent.BUTTON1:
                break;
            // 鼠标中键
            case MouseEvent.BUTTON2:
                break;
            // 鼠标右键
            case MouseEvent.BUTTON3:
                if (popupMenu == null) {
                    popupMenu = new JPopupMenu();
                    layer3DsTree.setComponentPopupMenu(popupMenu);
                    popupMenu.setLocation(e.getLocationOnScreen());
                } else {
                    popupMenu.removeAll();
                    popupMenu.setVisible(false);
                }

                TreeNodeData selectedTreeNode = Helper.getSelectedTreeNode(layer3DsTree);
                if (selectedTreeNode == null) {
                    return;
                }

                NodeDataType nodeType = selectedTreeNode.getType();
                // 普通图层右键菜单
                if (nodeType == NodeDataType.LAYER3DS) {
                    Object layer3DsData = selectedTreeNode.getData();
                    if (layer3DsData instanceof Layer3Ds) {
                        initLayer3DsContextMenu(popupMenu, (Layer3Ds) layer3DsData);
                    }
                }
                // 三维数据集图层右键菜单
                else if (nodeType == NodeDataType.LAYER3DDATASET || nodeType == NodeDataType.LAYER3DKML
                        || nodeType == NodeDataType.LAYER3DMAP) {
                    Object layer3D = selectedTreeNode.getData();
                    if (layer3D instanceof Layer3D) {
                        initLayer3DDatasetContextMenu(popupMenu, (Layer3D) layer3D);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void initLayer3DsContextMenu(JPopupMenu popupMenu, Layer3Ds layer3Ds) {
        JMenuItem createNewKmlItem = new JMenuItem("新建KML");
        createNewKmlItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    String name = f.getName();
                    return f.isDirectory() || name.endsWith("kml");
                }

                @Override
                public String getDescription() {
                    return "*.kml";
                }
            });
            int result = fileChooser.showSaveDialog(layer3DsTree.getRootPane().getParent());
            switch (result) {
                case JFileChooser.APPROVE_OPTION:
                    File selectedKmlFile = fileChooser.getSelectedFile();
                    Feature3Ds feature3Ds = new Feature3Ds();
                    try {
                        String kmlFileAbsolutePath = selectedKmlFile.getAbsolutePath();
                        Files.createFile(Paths.get(kmlFileAbsolutePath));
                        feature3Ds.toKMLFile(selectedKmlFile.getAbsolutePath());
                        layer3Ds.add(kmlFileAbsolutePath, Layer3DType.KML, true);
                        layer3DsTree.getScene().refresh();
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                    break;
                case JFileChooser.CANCEL_OPTION:
                    break;
                case JFileChooser.ERROR_OPTION:
                    break;
            }
        });
        popupMenu.add(createNewKmlItem);

        JMenuItem loadKmlLayer3DItem = new JMenuItem("加载KML");
        loadKmlLayer3DItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.addChoosableFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    String name = f.getName().toLowerCase();
                    return f.isDirectory() || name.endsWith("kml") || name.endsWith("kmz");
                }

                @Override
                public String getDescription() {
                    return "*.kml;*.kmz";
                }
            });
            int result = fileChooser.showOpenDialog(layer3DsTree.getRootPane().getParent());
            switch (result) {
                case JFileChooser.APPROVE_OPTION:
                    File selectedKmlFile = fileChooser.getSelectedFile();
                    layer3Ds.add(selectedKmlFile.getAbsolutePath(), Layer3DType.KML, true);
                    layer3DsTree.getScene().refresh();
                    break;
                case JFileChooser.CANCEL_OPTION:
                    break;
                case JFileChooser.ERROR_OPTION:
                    break;
            }
        });
        popupMenu.add(loadKmlLayer3DItem);
    }

    private void initLayer3DDatasetContextMenu(JPopupMenu popupMenu, Layer3D layer3D) {
        JMenuItem canEditItem = new JMenuItem("可编辑");
        canEditItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            layer3D.setEditable(!layer3D.isEditable());
        });
        popupMenu.add(canEditItem);

        JMenuItem ensureVisibleLayer3DByMillisecondsItem = new JMenuItem("缩放到本图层");
        ensureVisibleLayer3DByMillisecondsItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Rectangle2D layer3DBounds = layer3D.getBounds();
            Scene scene = layer3DsTree.getScene();
            scene.ensureVisible(layer3DBounds, 5000);
        });
        popupMenu.add(ensureVisibleLayer3DByMillisecondsItem);

        JMenuItem ensureVisibleLayer3DItem = new JMenuItem("快速定位到本图层");
        ensureVisibleLayer3DItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Scene scene = layer3DsTree.getScene();
            scene.ensureVisible(layer3D);
        });
        popupMenu.add(ensureVisibleLayer3DItem);

        JMenuItem importGeoModelItem = new JMenuItem("导入模型");
        importGeoModelItem.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    String name = f.getName();
                    return f.isDirectory() || name.endsWith("3ds") || name.endsWith("sgm");
                }

                @Override
                public String getDescription() {
                    return "*.3ds;*.sgm";
                }
            });
            int result = fileChooser.showOpenDialog(layer3DsTree.getRootPane().getParent());
            switch (result) {
                case JFileChooser.APPROVE_OPTION:
                    File selectedGeoModelFile = fileChooser.getSelectedFile();
                    GeoModel geoModel = new GeoModel();
                    if (geoModel.fromFile(selectedGeoModelFile.getAbsolutePath())) {
                        GeoStyle3D style3D = geoModel.getStyle3D();
                        if (style3D == null) {
                            style3D = new GeoStyle3D();
                            geoModel.setStyle3D(style3D);
                        }
                        Feature3Ds feature3Ds = layer3D.getFeatures();
                        if (feature3Ds != null) {
                            feature3Ds.add(geoModel);
                        }
                        layer3D.updateData();
                        layer3DsTree.reload();
                    }
                    break;
                case JFileChooser.CANCEL_OPTION:
                    break;
                case JFileChooser.ERROR_OPTION:
                    break;
            }
        });
        popupMenu.add(importGeoModelItem);

        JMenuItem layer3DStyleSettingItem = new JMenuItem("图层风格");
        layer3DStyleSettingItem.addActionListener(e -> {
            if (layer3D instanceof Layer3DDataset) {
                Layer3DDataset layer3DDataset = (Layer3DDataset) layer3D;
                Layer3DSetting additionalSetting = layer3DDataset.getAdditionalSetting();
                if (additionalSetting instanceof Layer3DSettingVector) {
                    Layer3DSettingVector layer3DSettingVector = (Layer3DSettingVector) additionalSetting;
                    GeoStyle3D geoStyle3D = layer3DSettingVector.getStyle();
                    geoStyle3D.setFillSymbolID(955820);
                    System.out.println();
                }
            }
        });
        popupMenu.add(layer3DStyleSettingItem);

        if (layer3D.getType() == Layer3DType.KML) {
            JMenuItem saveKmlItem = new JMenuItem("保存");
            saveKmlItem.addActionListener(e -> {
                popupMenu.setVisible(false);
                String kmlFilePath = layer3D.getDataName();
                Feature3Ds feature3Ds = layer3D.getFeatures();
                feature3Ds.toKMLFile(kmlFilePath);
            });
            popupMenu.add(saveKmlItem);
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
